import { Col, Form, Input, Row, Typography } from "antd";
import { useEffect, useState } from "react";
import { getItem } from "../../helpers/cart";
import Layout from "./Layout";
import CartItem from "./cartItem";
import PayButton from "./PayButton";

const { Title } = Typography

export default function Cart() {
    const [cartItem, setCart] = useState([])
    const [address, setAddress] = useState('')
    const [totalPrice, settotalPrice] = useState(0)
    useEffect(() => {
        setCart(getItem())
    }, [])

    useEffect(() => {
        let totalPrice = cartItem.reduce((currentValue, nextValue) => {
            return (currentValue += nextValue.count * nextValue.price)
        }, 0).toFixed(2)
        settotalPrice(totalPrice)
    }, [cartItem])
    let cartTable = () => {
        return (
            <table>
                <thead className="ant-table-thead">
                    <tr>
                        <th className="ant-table-cell">商品封面</th>
                        <th className="ant-table-cell">商品名称</th>
                        <th className="ant-table-cell">商品价格</th>
                        <th className="ant-table-cell">商品分类</th>
                        <th className="ant-table-cell">商品数量</th>
                        <th className="ant-table-cell">操作</th>
                    </tr>
                </thead>
                <tbody className="ant-table-tbody">
                    {cartItem.map(product => (<CartItem cartItem={setCart} key={product._id} product={product} />))}
                </tbody>
            </table>
        )
    }
    return (
        <Layout title='购物车' subTitle='与你同行'>
            <Row gutter={16}>
                <Col span='18'>
                    {cartTable()}
                </Col>
                <Col span='6'>
                    <Form.Item label='收获地址'>
                        <Input value={address} onChange={e => setAddress(e.target.value)} placeholder='请输入收货地址' />
                    </Form.Item>
                    <Title level={5}>总价：{totalPrice}</Title>
                    <PayButton totalPrice={totalPrice} address={address} cart={cartItem} />
                </Col>
            </Row>
        </Layout>
    )
}